package com.lyshop.jinding.activitys;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.lyshop.jinding.R;
import com.lyshop.jinding.adapters.FollowOrderAdapter;
import com.lyshop.jinding.base.BaseActivity;
import com.lyshop.jinding.bean.FollowGreatPeopleInfo;
import com.lyshop.jinding.bean.FollowOrderBean;
import com.lyshop.jinding.bean.FollowTradeInfo;
import com.lyshop.jinding.bean.FollowUserBean;
import com.lyshop.jinding.eventbus.EventCenter;
import com.lyshop.jinding.eventbus.EventConstants;
import com.lyshop.jinding.net.ActionCallbackListener;
import com.lyshop.jinding.utils.DataUtils;
import com.lyshop.jinding.utils.GlideUtils;
import com.lyshop.jinding.utils.MedalUtils;
import com.lyshop.jinding.utils.RouteUtil;
import com.lyshop.jinding.utils.ToastUtil;
import com.lyshop.jinding.utils.ToolbarUtils;
import com.lyshop.jinding.utils.Utils;
import com.lyshop.jinding.view.CreateOrderModule;
import com.zc.mychart.model.GoodsAllBean;
import com.zc.mychart.utils.ArithUtil;
import com.zc.mychart.utils.FormatUtil;

import java.util.ArrayList;
import java.util.List;

public class FollowOrderUserActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    private ImageView iv_user_header, iv_vip;
    private TextView tv_user_name, tv_follow, tv_fans, tv_is_follow, tv_follow_times, tv_profit_rate, tv_week_win_rate, tv_win_order, tv_empty, tv_follow_money_01, tv_follow_money_02, tv_follow_money_03;
    private LinearLayout ll_top_label, ll_order_desc;
    private RadioGroup rg_group;
    private SmartRefreshLayout refresh_layout;
    private RecyclerView rv_list;
    private NestedScrollView nsv_empty_scroll, nsv_scroll;
    private PieChart pie_chart;
    private String mUserId;
    private List<PieEntry> mPieEntrys;
    private final int TAB_FOLLOW_ORDER = 1;
    private final int TAB_TRADE_DETAIL = 0;
    private int mChooseIndex = TAB_TRADE_DETAIL;
    private FollowGreatPeopleInfo mDataInfo;
    private int maxOrderNumber;
    private List<Integer> mColors = new ArrayList<>();
    private boolean isAdd;
    private int mPageIndex = 1;
    private List<FollowOrderBean> mFollowOrderList;
    private FollowOrderAdapter mFollowAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ToolbarUtils.setStatusTextColor(true, this);
        mUserId = getIntent().getStringExtra(RouteUtil.BUNDLE_USER_ID);
        mPieEntrys = new ArrayList<>();
        initData();
    }

    private void initData() {
        mFollowOrderList = new ArrayList<>();
        mFollowAdapter = new FollowOrderAdapter();
        mFollowAdapter.setFollowOrderListener(new FollowOrderAdapter.FollowOrderListener() {
            @Override
            public void onClickDetail(String userId) {
            }

            @Override
            public void onClickFollow(int position) {
                if (mFollowOrderList == null || mFollowOrderList.isEmpty()) return;
                if (isUserValidLogin()) {
                    //更新用户信息
                    myApplication.updateUserDetail();
                    FollowOrderBean bean = mFollowOrderList.get(position);
                    GoodsAllBean mGroupBean = myApplication.getAllGoodMap().get(bean.pro_code);
                    if (null != mGroupBean) {
                        CreateOrderModule.getInstance().createOrder((BaseActivity) mContext, bean.trade_type, bean.order_id, mGroupBean, bean.unit_price, bean.user_id, 0);
                    } else {
                        ToastUtil.showToast(mContext, "未获取的产品信息");
                    }
                }
            }

            @Override
            public void onClickGoKLine(int position) {
                if (mFollowOrderList == null || mFollowOrderList.isEmpty()) return;

                FollowOrderBean bean = mFollowOrderList.get(position);
                GoodsAllBean mGroupBean = myApplication.getAllGoodMap().get(bean.pro_code);
                RouteUtil.toMarketActivity((BaseActivity) mContext, mGroupBean.pro_code);
            }
        });
        rv_list.setLayoutManager(new LinearLayoutManager(mContext));
        rv_list.setAdapter(mFollowAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (DataUtils.getUserId(mContext).equals(mUserId)) {
            tv_is_follow.setVisibility(View.GONE);
        }
        getFollowGreatUserInfo();
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_follow_order_user;
    }

    @Override
    protected void findViews() {
        iv_user_header = $(R.id.iv_user_header);
        tv_user_name = $(R.id.tv_user_name);
        iv_vip = $(R.id.iv_vip);
        tv_follow = $(R.id.tv_follow);
        tv_fans = $(R.id.tv_fans);
        tv_is_follow = $(R.id.tv_is_follow);
        tv_follow_times = $(R.id.tv_follow_times);
        ll_top_label = $(R.id.ll_top_label);
        tv_profit_rate = $(R.id.tv_profit_rate);
        tv_week_win_rate = $(R.id.tv_week_win_rate);
        tv_win_order = $(R.id.tv_win_order);
        rg_group = $(R.id.rg_group);
        refresh_layout = $(R.id.refresh_layout);
        rv_list = $(R.id.rv_list);
        nsv_empty_scroll = $(R.id.nsv_empty_scroll);
        tv_empty = $(R.id.tv_empty);
        nsv_scroll = $(R.id.nsv_scroll);
        tv_follow_money_01 = $(R.id.tv_follow_money_01);
        tv_follow_money_02 = $(R.id.tv_follow_money_02);
        tv_follow_money_03 = $(R.id.tv_follow_money_03);
        pie_chart = $(R.id.pie_chart);
        ll_order_desc = $(R.id.ll_order_desc);
    }

    @Override
    protected void setListeners() {
        rg_group.setOnCheckedChangeListener(this);
        refresh_layout.setEnableLoadMore(true);
        refresh_layout.setEnableRefresh(false);
        tv_is_follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFollow();
            }
        });
        refresh_layout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPageIndex++;
                getFollowRecordList();
            }
        });
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_trade_all:
                mChooseIndex = TAB_TRADE_DETAIL;
                break;
            case R.id.rb_trade_hold:
                mChooseIndex = TAB_FOLLOW_ORDER;
                break;
        }
        showPageData();
    }

    private void showPageData() {
        if (mChooseIndex == TAB_TRADE_DETAIL) {
            nsv_scroll.setVisibility(View.VISIBLE);
            nsv_empty_scroll.setVisibility(View.GONE);
            rv_list.setVisibility(View.GONE);
        } else {
            nsv_scroll.setVisibility(View.GONE);
            rv_list.setVisibility(View.VISIBLE);
        }
        switch (mChooseIndex) {
            case TAB_TRADE_DETAIL:
                setPieChart();
                break;
            case TAB_FOLLOW_ORDER:
                getFollowRecordList();
                break;
        }
    }

    private void getFollowRecordList() {
        if (mDataInfo == null) return;
        mAppAction.getMyFollowOrder(mPageIndex, mDataInfo.userId, new ActionCallbackListener<List<FollowOrderBean>>() {
            @Override
            public void onSuccess(List<FollowOrderBean> data) {
                completeRefresh();

                if (mPageIndex == 1){
                    if (data != null && data.size() > 0){
                        mFollowOrderList = data;
                    }else {
                        mFollowOrderList.clear();
                    }
                }else {
                    if (data != null && data.size() > 0){
                        mFollowOrderList.addAll(data);
                    }
                }

                if (data.size() == 10) {
                    refresh_layout.setEnableLoadMore(true);
                } else {
                    refresh_layout.setEnableLoadMore(false);
                }

                if (mFollowOrderList.size() > 0) {
                    rv_list.setVisibility(View.VISIBLE);
                    nsv_empty_scroll.setVisibility(View.GONE);
                    updateOrderList();
                } else {
                    rv_list.setVisibility(View.GONE);
                    nsv_empty_scroll.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void onFailure(String errorCode, String message) {
                completeRefresh();
                rv_list.setVisibility(View.GONE);
                tv_empty.setVisibility(View.VISIBLE);
                ToastUtil.showToast(mContext, message);
            }
        });
    }

    private void updateOrderList() {
        mFollowAdapter.setDataList(Utils.completionFollow(mFollowOrderList));
    }

    /**
     * 关闭刷新加载
     */
    private void completeRefresh() {
        refresh_layout.finishRefresh(1000);
        refresh_layout.finishLoadMore(1000);
    }

    private void addFollow() {
        if (!DataUtils.isLogin(mContext)) {
            onLogoutStatus();
        } else {
            FollowUserBean bean = new FollowUserBean();
            bean.userId = mUserId;
            if (mDataInfo.is_user_follow) {
                bean.type = 2;
                isAdd = false;
            } else {
                bean.type = 1;
                isAdd = true;
            }
            mAppAction.followUser(bean, new ActionCallbackListener<Void>() {
                @Override
                public void onSuccess(Void data) {
                    mDataInfo.is_user_follow = isAdd;
                    String toast = isAdd ? "已关注" : "已取消";
                    int count = isAdd ? 1 : -1;
                    mDataInfo.follow_me_count += count;
                    ToastUtil.showToast(mContext, toast);
                    showAddView();
                }

                @Override
                public void onFailure(String errorCode, String message) {
                    ToastUtil.showToast(mContext, message);
                }
            });
        }
    }

    /**
     * 获取当前用户信息
     */
    public void getFollowGreatUserInfo() {
        mAppAction.getFollowGreatPeopleInfo(mUserId, new ActionCallbackListener<FollowGreatPeopleInfo>() {
            @Override
            public void onSuccess(FollowGreatPeopleInfo data) {
                mDataInfo = data;
                tv_user_name.setText(data.nickname);
                tv_follow.setText(String.valueOf(data.me_follow_count));
                tv_profit_rate.setText(data.me_pro_loss_lv + "%");
                tv_week_win_rate.setText(data.win_lv + "%");
                tv_win_order.setText(String.valueOf(data.win_count));
                GlideUtils.showImageOptions(mContext, data.header_img, iv_user_header);
                MedalUtils.setUserCenterLevelTag(data.level, iv_vip);

                tv_follow_money_01.setText(FormatUtil.formatFollowMoney(data.win_money) + "元");
                tv_follow_money_02.setText(FormatUtil.formatFollowMoney(data.trade_deposit_sum) + "元");
                tv_follow_money_03.setText(FormatUtil.formatFollowMoney(data.pro_loss_sum) + "元");

                String followTimes = "被跟单次数 <font color=\"#E55C5C\">" + data.follow_order_count + "</font>";
                Utils.setHtmlText(tv_follow_times, followTimes);

                showAddView();
                addGoodsName();
                showPageData();
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showToast(mContext, message);
            }
        });
    }

    private void addGoodsName() {
        if (myApplication.getAllGoodMap() == null || myApplication.getAllGoodMap().isEmpty())
            return;
        for (int i = 0; i < mDataInfo.pro_list.size(); i++) {
            FollowTradeInfo info = mDataInfo.pro_list.get(i);
            info.goods_name = myApplication.getAllGoodMap().get(info.pro_code).pro_name;
            switch (i){
                case 0:
                    info.color = "#5B8FF9";
                    break;
                case 1:
                    info.color = "#F6BD16";
                    break;
                case 2:
                    info.color = "#7AB1CC";
                    break;
                case 3:
                    info.color = "#5AD8A6";
                    break;

            }
        }
    }

    private void showAddView() {
        if (DataUtils.getUserId(mContext).equals(mUserId)) {
            tv_is_follow.setVisibility(View.GONE);
        } else {
            if (mDataInfo.is_user_follow) {
                tv_is_follow.setBackgroundResource(R.drawable.border_gray_16_hollow_dp14);
                tv_is_follow.setTextColor(ContextCompat.getColor(mContext, R.color.color_gray_16));
                tv_is_follow.setText("已关注");
            } else {
                tv_is_follow.setText("+关注");
                tv_is_follow.setBackgroundResource(R.drawable.border_blue_07_solid_dp14);
                tv_is_follow.setTextColor(ContextCompat.getColor(mContext, R.color.white));
            }
        }
        tv_fans.setText(String.valueOf(mDataInfo.follow_me_count));
    }

    public void setPieChart() {
        if (null == mDataInfo) {
            return;
        }
        maxOrderNumber = 0;
        mPieEntrys.clear();
        pie_chart.clear();
        ll_order_desc.removeAllViews();

        for (FollowTradeInfo info : mDataInfo.pro_list) {
            maxOrderNumber += info.order_count;
        }

        for (FollowTradeInfo info : mDataInfo.pro_list) {
            float percent = 0;
            int tradeNum;
            if (maxOrderNumber > 0) {
                percent = (float) ArithUtil.mul(ArithUtil.div(info.order_count, maxOrderNumber), 100);
            }
            tradeNum = info.order_count;
            if (tradeNum > 0) {
                PieEntry entry = new PieEntry(percent, "");
                mPieEntrys.add(entry);
                mColors.add(Color.parseColor(info.color));
                View view = LayoutInflater.from(this).inflate(R.layout.item_order_desc, null, false);
                Drawable up = ContextCompat.getDrawable(this, R.drawable.icon_dot);
                Drawable drawableUp = DrawableCompat.wrap(up);
                DrawableCompat.setTint(drawableUp, Color.parseColor(info.color));
                ((ImageView) view.findViewById(R.id.iv_tips)).setImageDrawable(drawableUp);
                ((TextView) view.findViewById(R.id.tv_goods_name)).setText(info.goods_name);
                ((TextView) view.findViewById(R.id.tv_order_number)).setText(tradeNum + "单");
                ((TextView) view.findViewById(R.id.tv_order_rate)).setText(info.win_lv + "%");
                ll_order_desc.addView(view);
            }
        }

        if (mPieEntrys.size() == 0) {
            PieEntry entry = new PieEntry(100f, "");
            mPieEntrys.add(entry);
            mColors.add(Color.parseColor("#EBEBEB"));
        }

        PieDataSet dataSet = new PieDataSet(mPieEntrys, "");
        PieData pieData = new PieData(dataSet);

        //设置半透明圆环的半径, 0为透明
        pie_chart.setTransparentCircleRadius(0f);
        //设置初始旋转角度
        pie_chart.setRotationAngle(-15);
        pie_chart.setHoleRadius(65f);
        //数据连接线距图形片内部边界的距离，为百分数
        dataSet.setValueLinePart1OffsetPercentage(80f);
        dataSet.setColors(mColors);
        // 设置饼块之间的间隔
        dataSet.setSliceSpace(1f);
        // 不显示图例
        Legend legend = pie_chart.getLegend();
        legend.setEnabled(false);
        // 和四周相隔一段距离,显示数据
//        mPieChart.setExtraOffsets(26, 5, 26, 5);
        // 设置mPieChart图表是否可以手动旋转
        pie_chart.setRotationEnabled(false);
        // 设置piecahrt图表点击Item高亮是否可用
        pie_chart.setHighlightPerTapEnabled(false);
        // 设置mPieChart图表展示动画效果，动画运行1秒结束
        pie_chart.animateY(1000, Easing.EasingOption.EaseInOutQuad);
        //设置mPieChart是否只显示饼图上百分比不显示文字
        pie_chart.setDrawEntryLabels(true);
        //是否绘制PieChart内部中心文本
        pie_chart.setCenterTextSize(18f);
        pie_chart.setCenterTextColor(ContextCompat.getColor(this, R.color.color_black_01));
        pie_chart.setCenterText(generateCenterSpannableText());
        pie_chart.setHoleColor(ContextCompat.getColor(this, R.color.screen_bg));
        pie_chart.setDrawCenterText(true);
        // 绘制内容value，设置字体颜色大小
        pieData.setValueTextSize(0f);
        pie_chart.setData(pieData);
        Description description = new Description();
        description.setText("");
        pie_chart.setDescription(description);
        // 更新 piechart 视图
        pie_chart.postInvalidate();
    }

    private SpannableString generateCenterSpannableText() {
        SpannableString s = new SpannableString(maxOrderNumber + "单\n全部订单");
        s.setSpan(new RelativeSizeSpan(0.8f), String.valueOf(maxOrderNumber).length() + 1, s.length(), 0);
        s.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.color_black_03)),
                String.valueOf(maxOrderNumber).length() + 1, s.length(), 0);
        return s;
    }

    @Override
    protected void onEventComming(EventCenter eventCenter) {
        super.onEventComming(eventCenter);
        int event = eventCenter.getEventCode();
        switch (event) {
            case EventConstants.EVENTCODE_UPDATE_PRO_PRICE:
                updateOrderList();
                break;
        }
    }
}